<template>
  <div class="group-manage">
    <el-dialog title="提示" :visible.sync="dialogVisible" :before-close="handleClose" width="50%">
      <el-form ref="form" :rules="rules" :inline="true" :model="form" label-width="80px">
        <el-form-item label="帖子标题" prop="title">
          <el-input placeholder="请输入帖子标题" v-model="form.title"></el-input>
        </el-form-item>
        <el-form-item label="帖子内容" prop="content" style="display: block;">
          <el-input placeholder="请输入帖子内容" v-model="form.content" style="width: 1000px"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
                <el-button @click="cancel()">取 消</el-button>
                <el-button type="primary" @click="submit()">确 定</el-button>
            </span>
    </el-dialog>
    <div class="manage-header" style="margin-bottom: 30px;">
      <el-button @click="handleAdd()" type="primary" size="small">+ 发布新帖</el-button>
      <el-button @click="getPostList()" type="primary" size="small">获取帖子列表</el-button>
      <el-input v-model="searchValue" placeholder="请输入想要搜索的内容" style="width: 200px; margin-left: 30px; margin-right: 10px;" size="small" clearable/>
      <el-button @click="searchList()" type="primary" size="small">搜索</el-button>
    </div>

    <!-- user-namage 高度设置为90%了，这里把table设置为它的90% -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column prop="title" label="标题" width="180">
        <template slot-scope="scope">
          <div class="cell-content">
            <div v-html="scope.row.title"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="content" label="帖子内容" width="600">
        <template slot-scope="scope">
          <div class="post-content">
            <div v-html="scope.row.content"></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <span style="color: dodgerblue; cursor: pointer; margin-right: 10px" @click="toPostDetail(scope.row.id)">详情</span>
          <el-button @click="handleUpdate(scope.row)" size="small">修改</el-button>
          <el-button @click="deletePost(scope.row.id)" type="danger" size="small">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 固定在底部-->
    <div class="block" style="position: fixed; bottom: 0; width: 100%;">
      <el-pagination background layout="prev, pager, next" :total="totalCount" @current-change="handlePageChange">
      </el-pagination>
    </div>
  </div>
</template>

<script>
import requestUtil from '../../network/request'
import {getPostDetailFun} from '@/network/post/PostQuery'

export default {
  data() {
    return {
      dialogVisible: false,
      form: {
        id: '',
        title: '',
        content: ''
      },
      rules: {
        title: [
          {required: true, message: '请输入帖子标题'},
          {min: 1, max: 50, message: '长度在 1 到 50 个字符'}
        ],
        content: [
          {required: true, message: '请输入帖子内容'},
          {min: 1, max: 500, message: '长度在 1 到 500 个字符'}
        ]
      },
      tableData: [],
      opType: 'add', //add-新增 update-修改
      currentPage: 1, // 当前页
      pageSize: 10, // 页大小
      totalPage: 1,
      totalCount: 0,
      searchValue: ''
    };
  },
  methods: {
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          if ('add' === this.opType) {
            // 后续对表单数据的处理
            requestUtil.post('/post/add', this.form).then(res => {
              if (res.code === '0') {
                this.$message({
                  message: "新增成功",
                  type: 'success',
                  duration: 600 // 设置显示时间为 600 毫秒（0.6 秒）
                })
                this.getPostList()
              } else {
                this.$message.error(res.msg)
                //this.$message.error(res.msg, ˜600); // 错误消息也可以设置显示时间
              }
            })
          } else if ('update' === this.opType) {
            requestUtil.post('/post/update', this.form).then(res => {
              if (res.code === '0') {
                this.$message({
                  message: "更新成功",
                  type: 'success',
                  duration: 600 // 设置显示时间为 600 毫秒（0.6 秒）
                })
                this.getPostList()
              } else {
                this.$message.error(res.msg)
                //this.$message.error(res.msg, ˜600); // 错误消息也可以设置显示时间
              }
            })
          }
          this.handleClose()
        }
      })
    },
    cancel() {
      this.handleClose()
    },
    handleClose() {
      this.dialogVisible = false;
      this.$refs.form.resetFields()
    },
    handleAdd() {
      this.opType = 'add'
      this.dialogVisible = true
    },
    handleUpdate(row) {
      this.opType = 'update'
      this.dialogVisible = true
      // 注意这里需要对数据进行深拷贝，否则会出错 （有点类似java里的地址传递）
      this.form = JSON.parse(JSON.stringify(row))
    },
    searchList() {
      requestUtil.post('/post/searchList', {
        page: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        },
        searchValue: this.searchValue
      }).then(res => {
        if (res.code === '0') {
          const list = res.result
          // 确保 id 是字符串
          this.tableData = list.map(item => ({
            ...item,
            id: item.id.toString()
          }));
          this.totalCount = res.page ? res.page.totalCount : 0
        } else {
          this.$message.error({
            message: res.msg,
            duration: 2000,
            center: true,
            showClose: true
          })
        }
      })
    },
    getPostList() {
      requestUtil.post('/post/list', {
        page: {
          currentPage: this.currentPage,
          pageSize: this.pageSize
        }
      }).then(res => {
        if (res.code === '0') {
          const list = res.result
          // 确保 id 是字符串
          this.tableData = list.map(item => ({
            ...item,
            id: item.id.toString()
          }));
          this.totalCount = res.page ? res.page.totalCount : 0
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    deletePost(id) {
      requestUtil.post('/post/delete', {
        id: id
      }).then(res => {
        if (res.code === '0') {
          this.$message({
            message: "删除成功",
            type: 'success',
            duration: 600 // 设置显示时间为 600 毫秒（0.6 秒）
          })
          this.getPostList()
        } else {
          this.$message.error(res.msg)
          //this.$message.error(res.msg, ˜600); // 错误消息也可以设置显示时间
        }
      })
    },
    async toPostDetail(postId) {
      try {
        const res = await getPostDetailFun(postId);
        if (res.code === '0') {
          // 将帖子详情数据保存到路由状态中
          await this.$router.push({
            path: '/post/detail',
            query: {id: postId},
            state: {postDetail: res.result}
          });
        } else {
          this.$message.error('该帖子可能已被删除或不存在');
        }
      } catch (error) {
        console.error('Error checking post detail:', error);
        this.$message.error('检查帖子详情时出错');
      }
    },
    handlePageChange(currentPage) {
      this.currentPage = currentPage
      this.getPostList()
    }
  },
  mounted() {
    this.getPostList()
  }
};
</script>

<style lang="less" scoped>
.group-manage {
  height: 90%;
}
.cell-content {
  max-height: 50px; /* 根据需要调整 */
  overflow-y: auto;
}

.post-content {
  max-height: 200px; /* 根据需要调整 */
  /*overflow-y: auto;*/
}
</style>